package com.huang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huang.entity.Img;
import com.huang.service.ImgService;
import com.huang.util.Result;
import com.huang.vo.JournalDetailVo;
import com.huang.vo.UserJournalVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/journal")
public class JournalController {

    @Autowired
    private ImgService imgService;

    //请求日记简介和图片url
    @GetMapping("/{userId}")
    public Result getJournalList(@PathVariable("userId") String userId) {
        Long value = Long.valueOf(userId);
        List<Img> imgList = imgService.list(new LambdaQueryWrapper<Img>()
                .select(Img::getId,Img::getIntroduction,Img::getUserImg)
                .eq(Img::getUserId, value)
                .orderByDesc(Img::getCreateDate));
        ArrayList<UserJournalVo> journalVos = new ArrayList<>();
        for (Img img : imgList) {
            UserJournalVo journalVo = new UserJournalVo();
            BeanUtils.copyProperties(img, journalVo);
            journalVos.add(journalVo);
        }
        return Result.success(journalVos);
    }

    @GetMapping("/detail/{journalId}")
    public Result getJournalDetail(@PathVariable("journalId") String journalId) {
        Long value = Long.valueOf(journalId);
        Img one = imgService.getOne(new LambdaQueryWrapper<Img>()
                .select(Img::getCreateDate, Img::getUserImg, Img::getContent)
                .eq(Img::getId, value));
        JournalDetailVo journalDetailVo = new JournalDetailVo();
        BeanUtils.copyProperties(one,journalDetailVo);
        //将时间戳转为字符串
        journalDetailVo.setCreateDate(new DateTime(one.getCreateDate()).toString("yyyy-MM-dd"));
        return Result.success(journalDetailVo);
    }
    
    @PostMapping("/delete/{journalId}")
    public Result deleteJournal(@PathVariable("journalId") String journalId) {
        Long value = Long.valueOf(journalId);
        imgService.removeById(value);
        return Result.success("日记删除成功",null);
    }
}
